package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//用于验证Session 
public class SessionFilter implements Filter {
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		String requestURI=req.getRequestURI();
		String contextPath=req.getContextPath();
		
		//用户输入  /shop-admin  或   /shop-admin/login.jsp 都不用过滤
		if((!requestURI.equals(contextPath+"/"))  && (!requestURI.contains("login.jsp"))){
			HttpSession session=req.getSession();
			if(session.getAttribute("session_admin")==null){  //证明用户没登录
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().print("<script>window.top.location.href='"+contextPath+"/login.jsp?loginflag=0'</script>");
			}
			else{
				chain.doFilter(request, response);
			}
		}
		else{
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
